package com.jy.project.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jy.project.service.MaterialService;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.Random;


/**
 * @ClassName: CodeUtils
 * @Description: CodeUtils
 * @Author jwz
 * @Date 2021/5/7 8:52
 * @Version 1.0
 */
public class CodeUtils {
    public static String[] chars = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };


    public static String generateShortSnowflake() {
        String uuid = IdUtil.getSnowflake(1L,1L).nextIdStr();
        int length = uuid.length();
        String subStr=uuid.substring( length- 6, length);
        return subStr;

    }

    public static String generateShortUuid() {
        StringBuilder strBuilder=new StringBuilder();
        int i = new Random().nextInt(24);
        strBuilder.append(chars[i]);
        int i2 = new Random().nextInt(24);
        strBuilder.append(chars[i2]);
        String id= generateShortSnowflake();
        strBuilder.append(id);
        return strBuilder.toString();

    }

    public static String generateApplyNo(String applyType) {

        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(date);
        RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);
        String redisKey=applyType+format;
        Object o = redisUtils.get(redisKey);
        if (o==null){
            redisUtils.setNX(redisKey,0,60*60*24);
        }
        long incr = redisUtils.incr(redisKey,1);
        String applyNo = String.format("%04d", incr);//字符串格式化.
        return redisKey+applyNo;

    }


    public static String  generateMaterialNo(String assetClassNo) {
        RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int value = now.getMonth().getValue();
        String redisKey=assetClassNo;
        String yearStr=String.valueOf(year);
        if (yearStr.length()>=4){
            String month = String.format("%02d", value);//字符串格式化.
            String substrYear= StringUtils.substring(yearStr, 2, 4);
            redisKey=redisKey+ substrYear+month;
        }
        Object o = redisUtils.get(redisKey);
        if (o==null){
            MaterialService MaterialService = SpringUtil.getBean(MaterialService.class);
            Integer count = MaterialService.countByMaterialByAssetClass(assetClassNo);
            redisUtils.setNX(redisKey,count,60*30);
        }
        long incr = redisUtils.incr(redisKey,1);
        String materialNo = String.format("%04d", incr);//字符串格式化.
        return redisKey+materialNo;
    }

}
